﻿using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Safebrowsing
{
    /// <summary>
    /// Data for request for full hash
    /// More info here: http://code.google.com/apis/safebrowsing/developers_guide_v2.html#HTTPRequestForHashes
    /// </summary>
    public class HashRequest
    {
        /// <summary>
        /// Creates HashRequest for one prefix
        /// </summary>
        /// <param name="prefix"></param>
        public HashRequest(string prefix)
        {
            byte[] prefixBytes = Utils.HexToByte(prefix);
            PrefixSize = prefixBytes.Length;
            Prefixes = new List<byte[]> {prefixBytes};
        }

        /// <summary>
        /// Creates HashRequest data for a number of prefixes of the speicifed size
        /// </summary>
        /// <param name="prefixSize"></param>
        /// <param name="prefixes"></param>
        public HashRequest(int prefixSize, IEnumerable<string> prefixes)
        {
            PrefixSize = prefixSize;
            Prefixes = new List<byte[]>();
            foreach (string prefix in prefixes)
            {
                Prefixes.Add(Utils.HexToByte(prefix));
            }
        }

        internal List<byte[]> Prefixes { get; private set; }

        internal int PrefixSize { get; private set; }

        internal byte[] ToBytes()
        {
            using (var stream = new MemoryStream())
            {
                int length = PrefixSize*Prefixes.Count;
                string header = PrefixSize + ":" + length + Constants.LF;
                Utils.Write(stream, header, Utils.DefaultEncoding);
                foreach (byte[] prefix in Prefixes)
                {
                    stream.Write(prefix, 0, PrefixSize);
                }
                return stream.ToArray();
            }
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("Prefix Size: ");
            sb.Append(PrefixSize);
            sb.Append("; Prefixes: ");
            foreach (byte[] prefix in Prefixes)
            {
                sb.Append(Utils.ByteToHex(prefix));
                sb.Append(", ");
            }

            sb.Remove(sb.Length - 2, 2);
            return sb.ToString();
        }
    }
}
